import { Component, EventEmitter, Input, OnChanges, OnDestroy, OnInit, Output, Renderer2, SimpleChanges } from '@angular/core';
import { Setting } from '../../../public/setting/setting';
import { NzModalService } from 'ng-zorro-antd';
import { IdeService } from '../ide.service';
import { DeviceChargingState, DeviceState } from '../../../public/setting/enums';
import { ResponseConfig } from 'src/app/public/setting/model';

@Component({
  selector: 'app-device-data',
  templateUrl: './device-data.component.html',
  styleUrls: ['./device-data.component.scss']
})
export class DeviceDataComponent implements OnInit, OnChanges, OnDestroy {
  @Input() deviceData: string;
  @Input() hasBindDevice: boolean;

  @Output() needBindDevice = new EventEmitter();

  public deviceStates = DeviceState;
  public deviceState: string = DeviceState.offline;
  public deviceChargingStates = DeviceChargingState;
  public myDeviceElectricData: any = {};
  public showLogout = false;

  private logoutButtonListener: any;
  private electricTimer: any;

  constructor(private modalService: NzModalService,
    private ideService: IdeService,
    private renderer2: Renderer2) {
  }

  ngOnChanges(changes: SimpleChanges): void {
    if (changes && changes['deviceData'] && this.hasBindDevice) {
      if (Object.keys(this.deviceData).length > 0) {
        this.getDeviceElectric();
      }
    }
  }

  ngOnInit() {
    this.logoutButtonListener = this.renderer2.listen('document', 'click', (event) => {
      if (!event.path.some(item => item.className && typeof item.className === 'string' && item.className.indexOf('device-icon') >= 0)) {
        this.showLogout = false;
      }
    });
  }

  showBindDevice() {
    if (localStorage.getItem(Setting.storage.deviceData)) { return; }
    this.needBindDevice.emit(true);
  }

  /**
   * get device battery power every minutes
   */
  getDeviceElectric() {
    this.ideService.getDeviceElectric().subscribe((res: ResponseConfig) => {
      if (res && res.success) {
        this.deviceState = DeviceState.online;
        this.myDeviceElectricData = res.data;
        this.timeoutLoadDeviceElectric(60000);
      }
    }, err => {
      this.deviceState = DeviceState.offline;
      localStorage.removeItem(Setting.storage.deviceData);
      this.timeoutLoadDeviceElectric(60000);
    })
  }

  /**
   * Enable the timer after the first call is successful
   */
  timeoutLoadDeviceElectric(time) {
    const me = this;
    clearInterval(this.electricTimer);
    this.electricTimer = setTimeout(function () {
      me.getDeviceElectric();
    }, time);
  }

  ngOnDestroy(): void {
    if (this.logoutButtonListener) {
      this.logoutButtonListener();
    }
  }

}
